<?php
namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path') , EXT);

use app\admin\Controller;
use think\request;
use app\common\model\Knows;
use app\common\model\Questions;
use app\common\model\Questype;
use app\common\model\Sections;
use app\common\model\Subject;
use think\Db;
use think\Exception;
use think\Loader;
use think\Config;
use app\common\logic\DrawQuestion;
/**
 * 题库管理控制器 
 * 上传下载 修改题库 题库列表
 */

class Qbank extends Controller
{
    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];
	protected $model = null;

	//构造函数
	public function __construct(){	
		parent::__construct();
		//建立model对象
		$this->model = $this->getModel();
		
	}
	
	protected function filter(&$map)
    {
        if ($this->request->param("name")) {
            $map['name'] = ["like", "%" . $this->request->param("name") . "%"];
        }
       
    }
	
    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        $model = $this->getModel(); 
        // 列表过滤器，生成查询Map对象 
        // # ,$this->fieldReg => ['in',$child_plaforms] # 权限相关
        $child_plaforms = $_SESSION['think']['reg'];
		$map = $this->search($model, [$this->fieldIsDelete => $this::$isdelete,$this->fieldReg => ['in',$child_plaforms]]);
        // 特殊过滤器，后缀是方法名的

        $actionFilter = 'filter' . $this->request->action();
        if (method_exists($this, $actionFilter)) {
            $this->$actionFilter($map);
        }
		$QbankAssociation = new \app\common\model\QbankAssociation();

		$qb_id = $QbankAssociation->getListByArgAss($this->plaform,1);
		if(strpos($_SERVER['PHP_SELF'],'qbank/index') !== false || strpos($_SERVER['REQUEST_URI'],'qbank/index') !== false){
			$map['status<99 or (id'] = ['in',$qb_id];
			$map['status<99 ) and isdelete'] = 0;
		}

        // 自定义过滤器
        if (method_exists($this, 'filter')) {
            $this->filter($map);
        }

		// $statistics = self::statisticsup();
// var_dump($map);exit;
        $this->datalist($model, $map,'id,name,parentid,status,rule,remark,sort,isdelete,admin_reg,total,thumb,issharing'); 
		$this->view->assign("qb_id", $qb_id);
		$this->view->assign("statistics", $statistics);
        // var_dump($statistics);exit;
        return $this->view->fetch();
    }
	
	
	    /**
     * 编辑
     * @return mixed
     */
    public function add()
    {
		$controller = $this->request->controller();

        if ($this->request->isAjax()) {
			
            // 更新
            $data = $this->request->post();
            if (!empty($data['data_rule'][0]) && empty($data['ratio'])){
                $data['ratio'] = $data['data_rule'][0];
                $data['ratio'] = str_replace(',',PHP_EOL,$data['ratio']);
                $ob_dw = new DrawQuestion();
                $data['ratio'] = $ob_dw->enRation($data['ratio']);
                unset($data['data_rule'][0]);
            }

            $data['create_time'] = time();
                $data['scores'] = 0;
             
             if($data['parentid']>0){
                $data['creditsettingid'] = 0;
                $data['scores'] = 0;
                //分题库上级alltype
                $topalltype = $this->getModel($controller)->where(['id'=>$data['parentid']])->field('alltype')->find();
                $data['alltype'] = $topalltype['alltype'];
            }else{
                // 顶级题库修改题型 sunman
                if(!empty($data['alltype']['questypes'])){
                 $data['alltype']=serialize($data['alltype']);
                } else {
                    //为空说明是分题库 分题库直接查询顶级题库的alltype
                    $data['alltype']=serialize([]);
                }    
            }

            
            // 验证
            if (class_exists($validateClass = Loader::parseClass(Config::get('app.validate_path'), 'validate', $controller))) {
                $validate = new $validateClass();
                if (!$validate->check($data)) {
                    return ajax_return_adv_error($validate->getError());
                }
            }
			
            $data['admin_reg'] = "text";
			$r_status = $this->model->DataSave($data); 
			$result_txt = $r_status ?  '新增加成功': $this->model->getError();	
			
			return ajax_return_adv($result_txt);
        } else {
            $param = $this->request->param();
            // 编辑显示
            $qbank_conf = $this->model->getInfo($id);
			$qbank_list = $this->model->getQbankList();
			$SubjectModel  = new Subject();
			$QuestypeModel  = new Questype();
            $Questions = new Questions();
            $subjectList = $SubjectModel->subject();
            $questionType = $QuestypeModel->getQuestypeList(['status'=>1,'isdelete'=>0],'id,type type_name');
//            $questionNum = $result[0];
			$this->view->assign("question_type", $questionType); //题型list
			$this->view->assign("subject", $subjectList);
			$this->view->assign("qbanks", $qbank_list);
            $this->view->assign("vo", $qbank_conf);
            // self::v($questionType);exit();
            return $this->view->fetch('edit');
        }
    }
	
    /**
     * 编辑
     * @return mixed
     */
    public function edit()
    {
        $controller = $this->request->controller();

        if ($this->request->isAjax()) {
			
            // 更新
            $data = $this->request->post(); 
            if (!empty($data['data_rule'][0]) && empty($data['ratio'])){
                $data['ratio'] = $data['data_rule'][0];
                $data['ratio'] = str_replace(',',PHP_EOL,$data['ratio']);
                $ob_dw = new DrawQuestion();
                $data['ratio'] = $ob_dw->enRation($data['ratio']);
                unset($data['data_rule'][0]);
            }

            if (!$data['id'])  return ajax_return_adv_error("缺少参数ID");
		if(empty($data['creditsettingid'])){
                $data['scores'] = 0;
            }
            if($data['parentid']>0){
                $data['creditsettingid'] = 0;
                $data['scores'] = 0;
                //分题库上级alltype
                $topalltype = $this->getModel($controller)->where(['id'=>$data['parentid']])->field('alltype')->find();
                $data['alltype'] = $topalltype['alltype'];
            }else{//顶级题库获取alltype 
                // 顶级题库修改题型
                if(!empty($data['alltype']['questypes'])){
                 $data['alltype']=serialize($data['alltype']);
                } else {
                    $data['alltype']=serialize([]);
                }
            }
			if(!$data['parentid']){ //如果为false 就是大题库
              //  $child_plaform = getChildAdminRegByPlaformId($this->plaform);
				$questions = new \app\common\model\Questions();
			//	$ques = Db::table($questions->tablename())->where(['admin_reg'=>['in',$child_plaform],'q_status'=>1,'isdelete'=>0])->field('count(*) as num')->find();
				$ques = Db::table("agk_questions")->where(['admin_reg'=>$_SESSION["think"]["reg"],'q_status'=>1,'isdelete'=>0,'q_qbankid'=>$data['id']])->field('count(*) as num')->find();
				if(empty($ques['num'])) $ques['num']=0;
				$qbank = new \app\common\model\Qbank();
				$data['total'] = $ques['num']; 
			} else {
				$data['total'] = 0;
			}
			
            // 验证
            if (class_exists($validateClass = Loader::parseClass(Config::get('app.validate_path'), 'validate', $controller))) {
                $validate = new $validateClass();
                if (!$validate->check($data)) {
                    return ajax_return_adv_error($validate->getError());
                }
            }

			$r_status = $this->model->DataSave($data); 
			$result_txt = $r_status ?  '编辑成功': $this->model->getError();	
			
			return ajax_return_adv($result_txt);
        } else {
            // 编辑显示
            $id = $this->request->param('id');
            if(!$id) throw new HttpException(404, "缺少参数ID");			
            $qbank_conf = $this->model->getInfo($id);
            // 顶级题库绑定题型 如果顶级题库选择了题型 不进入二级
            if($qbank_conf['parentid']==0){
                $this->view->assign("vo_ratio",unserialize($qbank_conf['alltype']));
            }else{
                $pid_conf = $this->model->getInfo($qbank_conf['parentid']);
                $this->view->assign("vo_ratio",unserialize($pid_conf['alltype']));
            }
			$ob_dw = new DrawQuestion();
            $Subject = new Subject();
            $QuestypeModel = new Questype();
            $KnowsModel = new Knows();
            $ratio = $ob_dw->deRation($qbank_conf['ratio'],3);
            
			$qbank_conf['ratio'] = $ob_dw->deRation($qbank_conf['ratio'],2);

            foreach ($ratio as $kkk=>$cc){
                $ratio[$kkk][4] = implode(':',$cc);
            }
			$qbank_list = $this->model->getQbankList();
          //  $child_plaform = getChildAdminRegByPlaformId($this->plaform);

            //根据科目id 获取下面的 章节和知识点end
            $questionType = $QuestypeModel->getQuestypeList(['status'=>1,'isdelete'=>0],'id,type type_name');
           // $KnowsList = $KnowsModel->getKonwsListByArg(['status'=>1,'isdelete'=>0,'admin_reg'=>['in',$child_plaform]],'id,k_name');
		   
			$KnowsList = $KnowsModel->getKonwsListByArg(['status'=>1,'isdelete'=>0,'admin_reg'=>$_SESSION["think"]["reg"]],'id,k_name');
            $KnowsList = setArrKeyId($KnowsList);
            $questionType = setArrKeyId($questionType);
            $subjectList = $Subject->subject();

	
			
			/**针对继承的题库**/
			$id = Db::name('qbank_association')->field('qb_id')->where(['qb_id'=> $qbank_conf["parentid"],'marks'=>0,'status'=>0])->find();
			if(!empty($id['qb_id'])){
				$qbankid = Db::name('qbank')->field('parentid')->where(['id'=>$id['qb_id']])->find();
				if($qbankid['parentid']){
					$tabe = 'question_db';
				} else {
					$tabe = 'questions';
				}
				$q_subjectid = Db::name($tabe)->field('distinct q_subjectid')->where(['q_qbankid'=>$id['qb_id']])->select();
				
				$subjectList = $Subject->subjectAll($q_subjectid);
			
			}
			/**针对继承的题库**/
		
			
			// $qbank_conf['ratio']=unserialize($qbank_conf['ratio']);

            $this->view->assign("KnowsList", $KnowsList);
            $this->view->assign("subject", $subjectList);
            $this->view->assign("question_type", $questionType);
			$this->view->assign("u_ratio", $ratio);
			$this->view->assign("ratio", $qbank_conf['ratio']);
			$this->view->assign("qbanks", $qbank_list);
            $this->view->assign("vo", $qbank_conf);
            
            return $this->view->fetch();
        }
    }
    

	
	
/*	public function lookQuestionDb()
    {
        $bank_id = $this->request->param('bank_id');
        $model = $this->getModel('QuestionDb');
        // 列表过滤器，生成查询Map对象
        $map = $this->search($model, [$this->fieldIsDelete => $this::$isdelete, $this->fieldReg => ['in',$child_plaform], 'q_qbankid' => $bank_id]);
   
        // 特殊过滤器，后缀是方法名的
        $actionFilter = 'filter' . $this->request->action();
        if (method_exists($this, $actionFilter)) {
            $this->$actionFilter($map);
        }
        // 自定义过滤器
        if (method_exists($this, 'filter')) {
            $this->filter($map);
        }
        $model = new \app\common\model\QuestionDb();
        $this->datalist($model, $map);
        return $this->view->fetch();
    }*/
	
	
	/* 新增加函数 按规则生成分题库试题 */
	public function ajaxGenerateQuestion($id)
	{
		if(empty($id)) return false;
		$qbank_conf = $this->getModel()->find($id);
		if(empty($qbank_conf)) return false;
			
		$ob_dw = new DrawQuestion();

		$questions = $ob_dw->randomDrawQues($qbank_conf['parentid'],$qbank_conf['ratio'],1);
	
		foreach($questions as $val){
			foreach($val as $v){
				$v['q_qbankid'] = $id;
				$ques_arr[] = $v;
			}
		}
		
		//批量写入到分题库中
		//先清空以前试题
		model('QuestionDb')->where(['q_qbankid'=>$id])->delete();
		$ret = model('QuestionDb')->batDataSave($ques_arr);

		$this->getModel()->where('id',$id)->setField(['generate'=>1]);

		$qbank = new \app\common\model\Qbank();
		Db::table("agk_qbank")->where('id', $id)->update(['total'  => count($ques_arr)]);

		return ajax_return_adv("题库试题生成成功！");

		
	}
	
	/* 导出题库 */
	public function download()
	{
	
		$id = $this->request->param('bank_id');
		$cid = $this->request->param('cid');  
		$qbank = new \app\common\model\Qbank();   
		$child_plaforms = [$_SESSION["think"]["reg"]];
		$QbankAssociation = new \app\common\model\QbankAssociation();
		$qbank_adminreg = $QbankAssociation->getAdminReg($this->plaform,$id);
		if($qbank_adminreg){
			$child_plaforms[] = $qbank_adminreg;
		}
		$plaform_parentid = Db::name('plaform')->field('parentid')->find();

		if($plaform_parentid['parentid']){
			
			$upadmin = Db::name('plaform')->field('admin_reg')->where(['id'=>$plaform_parentid['parentid']])->find();
			$child_plaforms[] = $upadmin['admin_reg'];
		}
	 
		$qban = Db::table("agk_qbank")->where(['isdelete'=>0,'id' =>$id])->find(); 
		if (!$id || empty($qban['name'])){  echo "没有任何数据，请核对试题是否存在";exit; }
		if($cid){
			$questions = new \app\common\model\Questions();
		} else {
			$questions = new \app\common\model\QuestionDb();
		}
		$header = [ '题型','试题内容', '试题答案', '试题选项','选项数量']; 
		$ques = Db::table("agk_questions")->where(['isdelete'=>0,'q_qbankid' =>$id])->field('q_typeid,q_question,q_answer,q_select,q_selectnumber')->order("id desc")->select(); 
		ob_clean();

		if ($error = \Excel::export($header, $ques, $qban['name'], '2007')) {
			throw new Exception($error);
		}
	}
    /**
     * 保存排序
     */
    public function saveOrder()
    {
        $param = $this->request->param();
//        if (!isset($param['sort'])) {
//            return ajax_return_adv_error('缺少参数');
//        }

        $model = $this->getModel();//$child_plaform = getChildAdminRegByPlaformId($this->plaform);
        foreach ($param['sort'] as $id => $sort) {
            $model->where('id', $id)->update(['sort' => $sort]);
        }

        return ajax_return_adv('保存排序成功', '');
    }

    /**
     *
     */

    public function sharing(){
        if ($this->request->isAjax()) {
            $data = $this->request->post();
            $sharing_qbank_id = $data['parentid'];
	
            if (empty($sharing_qbank_id)){
                return ajax_return_adv_error("请选择一个共享题库");
            }
            // 简单的直接使用db写入
            Db::startTrans();
            try {
                //根据共享题库ID 复制题库到本平台
                $qbankInfo =  Db::name('qbank')->where(['id'=>$sharing_qbank_id])->find();
                if (empty($qbankInfo))return ajax_return_adv_error("参数有误");
                $res = $qbankInfo['parentid']==0?0:1;

                $ob_dw = new DrawQuestion();
                $qbankInfo['admin_reg'] = $_SESSION['think']['reg'];
                $ratio = $ob_dw->deRation($qbankInfo['ratio']);
                if (!empty($ratio)){
                    $knowsid = array_column($ratio,0);
                    //根据知识点ID反向获取科目与章节
                    $knowsList = Db::name('knows')->where(['id'=>['in',$knowsid]])->select();
                    $result = $this->resultInsert($knowsList);
                    foreach ($ratio as &$value){
                        foreach ($result as $kk=>$tt){
                            if ($kk==$value[0]){
                                $value[0]=$tt;
                            }
                        }
                        $value = implode(':',$value);
                    }
                    $ratio = serialize($ratio);



                }
                $data = [
                    'name'=>$qbankInfo['name'],
                    'parentid'=>$qbankInfo['parentid'],
                    'status'=>$qbankInfo['status'],
                    'issharing'=>$qbankInfo['issharing'],
                    'rule'=>$qbankInfo['rule'],
                    'remark'=>$qbankInfo['remark'],
                    'create_time'=>time(),
                    'update_time'=>time(),
                    'sort'=>$qbankInfo['sort'],
                    'admin_id'=>$qbankInfo['admin_id'],
                    'admin_reg'=>$_SESSION['think']['reg'],
                    'isdelete'=>$qbankInfo['isdelete'],
                    'ratio'=>$ratio,
                    'level'=>$qbankInfo['level'],
                    'generate'=>$qbankInfo['generate'],
                    'total'=>$qbankInfo['total'],
                    'thumb'=>$qbankInfo['thumb'],
                    'creditsettingid'=>$qbankInfo['creditsettingid'],
                    'scores'=>$qbankInfo['scores'],
					//'afterinher'=>0,
                ];
			
                $id =  Db::name('qbank')->insert($data,false,true);
				//$QbankAssociation = new \app\common\model\QbankAssociation();
				//$QbankAssociation->where(['plaformid'=>$this->plaform,'qb_id'=>$sharing_qbank_id,'marks'=>0])->update(['afterinher'=>$id]);

                if ($res==0){
                    $table = 'questions';
                }else{
                    $table = 'question_db';
                }
                $quesLists =  Db::name($table)->where(['q_qbankid'=>$sharing_qbank_id])->select();
				$skid = self::reverses($sharing_qbank_id);
                if (!empty($quesLists)){
                    foreach ($quesLists as &$v) {
                        if ($res==0){
                            unset($v['id']);
                        }else{
                            unset($v['db_id']);
                        }
                        $v['q_qbankid'] = $id;
                        $v['q_create_time'] = time();
                        foreach ($result as $kk=>$tt){
                            if ($kk==$v['q_knowsid']){
                                $q_knowsid = $tt;
                                $v['q_knowsid'] = $tt;
                            }
                        }
						/*
                        $knowsInfo = Db::name('knows')->field('k_subjectid,k_sectionid')->where(['id'=>$q_knowsid])->find();
						if(!empty($knowsInfo['k_subjectid'])){
                        $v['q_subjectid'] = $knowsInfo['k_subjectid'];
						}
						if(!empty($knowsInfo['k_sectionid'])){
                        $v['q_sectionid'] = $knowsInfo['k_sectionid'];
						}
						*/
						$v['q_subjectid'] = $skid['subjectid'][$v['q_subjectid']];
						$v['q_sectionid'] = $skid['sectionid'][$v['q_sectionid']];
						$v['q_knowsid'] = $skid['knowsid'][$v['q_knowsid']];
						
						$v['admin_reg'] = $_SESSION['think']['reg'];
                        $qid = Db::name($table)->insert($v, FALSE, TRUE);
                    }
                }
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ajax_return_adv_error($e->getMessage());
            }
			
			$QbankAssociation = new \app\common\model\QbankAssociation();
			//$QbankAssociation->where(['plaformid'=>$this->plaform,'qb_id'=>$sharing_qbank_id])->delete();
			$QbankAssociation->where(['plaformid'=>$this->plaform,'qb_id'=>$sharing_qbank_id,'marks'=>0])->update(['status'  => 1]);
           return ajax_return_adv('添加成功');
        }else{
            $parent_plaform = getParentAdminRegByPlaformId($this->plaform);
            //获取父平台开启共享题库的
            $qbanks =[];
            if (!empty($parent_plaform)){
                $parent_plaform = array_unique($parent_plaform);
                //根据上级admin_reg 获取上级题库
                $qbanks =  Db::name('qbank')->where(['admin_reg'=>['in',$parent_plaform],'issharing'=>1])->field('id,name')->select();
            }
            $this->view->assign("qbanks", $qbanks);
            return $this->view->fetch();
        }

    }


    /**
     * 临时方法 循环查询 科目章节 知识点
     */
    public function resultInsert($result){
		return false;
       // if (empty($result))return false;
        $SubjectModel = new Subject();
        $SectionsModel = new Sections();
        $KnowsModel = new Knows();//ex_knows
        $rr = [];
        // 简单的直接使用db写入
        Db::startTrans();
        try {
            foreach ($result as $key=>$value){
                $kid = $value['id'];
                $subjectid = $value['k_subjectid'];
                $sectionid = $value['k_sectionid'];
                $sql = "replace into ex_subject(s_name,s_setting,status,isdelete,admin_id,admin_reg) SELECT s_name,s_setting,status,isdelete,admin_id,'{$_SESSION['think']['reg']}' from ex_subject where id = {$subjectid}";
                $SubjectModel->execute($sql);
                $subid = $SubjectModel->getLastInsID();
                $sql = "replace into ex_sections(se_name,se_subjectid,se_describe,status,admin_id,admin_reg,isdelete) SELECT se_name,{$subid},se_describe,status,admin_id,'{$_SESSION['think']['reg']}',isdelete from ex_sections where id = {$sectionid}";
                $SectionsModel->execute($sql);
                $secid = $SectionsModel->getLastInsID();
                $sql = "replace into ex_knows(k_name,k_subjectid,k_sectionid,k_describe,k_status,isdelete,admin_id,status,admin_reg,remark) SELECT k_name,{$subid},{$secid},k_describe,k_status,isdelete,admin_id,status,'{$_SESSION['think']['reg']}',remark from ex_knows where id = {$kid}";
                $KnowsModel->execute($sql);
                $knoid = $KnowsModel->getLastInsID();
                $rr[$kid] = $knoid;
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ajax_return_adv_error($e->getMessage());
        }
        return $rr;
    }
	
	/*
	*继承题库列表
	*/
	 public function inherit()
    {
	//var_dump($_SESSION);exit;
        $model = $this->getModel();
		$adminUser = new \app\common\model\AdminUser();

		$plaforms = $adminUser->field('plaform_id')->where(['reg'=>$_SESSION["think"]["reg"]])->find();

			$this->plaform=$plaforms->plaform_id;
       // $child_plaform = getChildAdminRegByPlaformId($this->plaform);
		if ($this->request->isAjax()) {
			$data = $this->request->post();

			
			if(empty($data['id'])){
				if(isset($data['cid']) && !empty($data['cid'])){
					$data['id'][] = $data['cid'];
					
				} else {
					return ajax_return_adv_error("请选择要导入的题库");
				}
				
			}
			$id= $data['id'];
			$QbankAssociation = new \app\common\model\QbankAssociation();
			$qb_id = $QbankAssociation->getListByArgAss($this->plaform);
			$inser = array();
			$datime = date('Y-m-d H:i:s');
			if(empty($qb_id)){
				foreach($id as $v){
					
					$inser[] = [
								'qb_id' => $v,
								'add_name' => $_SESSION["think"]['real_name'],
								'add_time' => $datime,
								'plaformid' => $this->plaform,
								];
				}
				
			} else {
				foreach($id as $v){
				
					if(!in_array($v,$qb_id)){
						$inser[] = [
									'qb_id' => $v,
									'add_name' => $_SESSION["think"]['real_name'],
									'add_time' => $datime,
									'plaformid' => $this->plaform,
									];
					}
				}
			}
			if(!empty($inser)){
				Db::startTrans();
                try {
					
                   $QbankAssociation->insertAll($inser);
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();

                    return ajax_return_adv_error($e->getMessage());
                }
			}
			return ajax_return_adv('继承题库成功');
		} else {
			/*
			$child_plaform = getSonAdminRegByPlaformId($this->plaform,0);
			array_push($child_plaform,'abcdef'); //这里是查询他上级到最顶级的所有 id
			*/
		
			/****修改为只查询上一级***/
			$rplaform = Db::name('plaform');
			$result = $rplaform->field('parentid,qbankid')->where(['id'=>$this->plaform])->find();
			$child_plaform = $rplaform->field('admin_reg')->where(['status'=>1,'id'=>$result['parentid']])->find();


			/****修改为只查询上一级 end***/
			$child_plaform['admin_reg'] = empty($child_plaform['admin_reg']) ? 'j2og00bs_4b4brpghsk6c591816198a76cadmin' : $child_plaform['admin_reg'];
			$QbankAssociation = new \app\common\model\QbankAssociation();
			$qb_id = $QbankAssociation->getListByArgAss($this->plaform);
	
			// 列表过滤器，生成查询Map对象
			$map = $this->search($model, [$this->fieldIsDelete => $this::$isdelete,$this->fieldReg => $child_plaform['admin_reg']]);
		   // $map = $this->search($model, [$this->fieldIsDelete => $this::$isdelete,$this->fieldReg => ['in',$child_plaform]]);//这里是查询他上级到最顶级的所有 数据
			//$map = $this->search($model, [$this->fieldIsDelete => $this::$isdelete]);
			// 特殊过滤器，后缀是方法名的
			$actionFilter = 'filter' . $this->request->action();
	
			if (method_exists($this, $actionFilter)) {
				$this->$actionFilter($map);
			}
			$idArr = array('asss');
			if(!empty($result['qbankid'])){
				$qbankid = explode(',',str_ireplace('|','',$result['qbankid']));
				for($i=1;$i<count($qbankid);$i++){
					$idArr[] = $qbankid[$i];
				}
			}

			$map['id'] = ['in',$idArr];
			if(!empty($qb_id)){
				
				$map[' id'] = ['not in',$qb_id];
			}
			// 自定义过滤器
			if (method_exists($this, 'filter')) {
				$this->filter($map);
			}

			$this->datalist($model, $map,'id,name,parentid,status,rule,remark,sort,isdelete,admin_reg,total,thumb,issharing');

			return $this->view->fetch();
		}
    }
	
	/*
	*统计数量 题库
	*/
	 public function statisticsup()
    {

		$QbankAssociation = new \app\common\model\QbankAssociation();
		$Qbank = new \app\common\model\Qbank();
		$qb_id = $QbankAssociation->getListByArgAss($this->plaform);
		$result = Db::name('plaform')->field('qbankid')->where(['status'=>1,'id'=>$this->plaform])->find();  

		$idArr = array();
			if(!empty($result['qbankid'])){
				$qbankid = explode(',',str_ireplace('|','',$result['qbankid']));
			
				unset($qbankid[0]);
				$exis_id = $Qbank->getListByArg(['id'=>['in',$qbankid],'isdelete'=>0],'id');
			$cc = array();
				foreach($exis_id as $v){
					$cc[] = $v->id;
					if(!in_array($v->id,$qb_id)){
							$idArr[] = $v->id;
					}
				}
	
			}
	
		$num = count($idArr);
		$feedback = ['code'=>0,'num'=>0];
		if($num){
			$feedback = ['code'=>1,'num'=>$num];
		}
		return $feedback;
		
	}
	
	 public function inherits(){
	 if ($this->request->isAjax()) {
		$SubjectModel  = new Subject();
		$subjectList = $SubjectModel->subject();
		$qbankids = (int)$this->request->param('qbankid');
		if(!$qbankids){
			return json_encode($subjectList);
		}
		
		$id = Db::name('qbank_association')->field('qb_id')->where(['qb_id'=>$qbankids,'marks'=>0,'status'=>0])->find();
	
		if(empty($id['qb_id'])){
			$id = array();
			$afterinher_id = Db::name('qbank')->field('afterinher')->where(['id'=>$qbankids])->find();
			if(!empty($afterinher_id["afterinher"])){ $id['qb_id']=$afterinher_id["afterinher"]; }

		}
		
		
		if(!empty($id['qb_id'])){
		$qbankid = Db::name('qbank')->field('parentid,id')->where(['id'=>$id['qb_id']])->find();
		if(empty($qbankid['id'])){
			$qbankid = Db::name('qbank')->field('parentid,id')->where(['id'=>$qbankids])->find();
			$id['qb_id'] = $qbankids;
		}

			if($qbankid['parentid']){
				$tabe = 'question_db';
			} else {
				$tabe = 'questions';
			}
			$q_subjectid = Db::name($tabe)->field('distinct q_subjectid')->where(['q_qbankid'=>$id['qb_id']])->select();

			$subjectList = $SubjectModel->subjectAll($q_subjectid);
			
		}
		
	
		//array(1) { [0]=> array(2) { ["id"]=> int(106) ["s_name"]=> string(1) "1" } } ex_qbank
		return json_encode($subjectList);
	 }
		
	}
	
	/*
	*查询被继承题库的 章节 科目 id
	*/
	 private function reverses($sharing_qbank_id=0){ // private
		if(!$sharing_qbank_id) return false;

		/*******获取当前题库的科目 章节 知识点*******/
		$qbank = new \app\common\model\Qbank();
		$qbanks  = $qbank->getListByArgDetails($sharing_qbank_id);
		$datas_control = ['subjectid'=>[],'sectionid'=>[],'knowsid'=>[]];
		$SubjectModel = new Subject();
        $SectionsModel = new Sections();
        $KnowsModel = new Knows();
		
		/**对照 科目**/
		foreach($qbanks['subjectid'] as $v){
			$subjectid_id = Db::name('subject')->field('id')->where(['orid'=>$v,'admin_reg'=>$_SESSION["think"]["reg"]])->find();
			if(empty($subjectid_id['id'])){
				$subjectid_de = Db::name('subject')->field('*')->where(['id'=>$v])->find();
				unset($subjectid_de['id']);
				$subjectid_de['admin_id'] = $_SESSION["think"]["auth_id"];
				$subjectid_de['admin_reg'] = $_SESSION["think"]["reg"];
				$subjectid_de['orid'] = $v;
				$id = Db::name('subject')->insertGetId($subjectid_de);
				$datas_control['subjectid'][$v] = $id;
				
				
			} else {
				$datas_control['subjectid'][$v] = $subjectid_id['id'];
			}
			
		}
		
		/**对照 章节**/
		foreach($qbanks['sectionid'] as $vs){
			$sections_id = Db::name('sections')->field('id')->where(['orid'=>$vs,'admin_reg'=>$_SESSION["think"]["reg"]])->find();
			if(empty($subjectid_id['id'])){
				$sections_de = Db::name('sections')->field('*')->where(['id'=>$vs])->find();
				unset($sections_de['id']);
				$sections_de['admin_id'] = $_SESSION["think"]["auth_id"];
				$sections_de['admin_reg'] = $_SESSION["think"]["reg"];
				$sections_de['orid'] = $vs;
				$sections_de['se_subjectid'] = $datas_control['subjectid'][$sections_de['se_subjectid']];
				$id = Db::name('sections')->insertGetId($sections_de);
				$datas_control['sectionid'][$vs] = $id;
			

			} else {
				$datas_control['sectionid'][$vs] = $vs;
			}
		
		}
		
		/**对照 知识点**/
		foreach($qbanks['knowsid'] as $vk){
			$knows_id = Db::name('knows')->field('id')->where(['orid'=>$vk,'admin_reg'=>$_SESSION["think"]["reg"]])->find();
			if(empty($knows_id['id'])){
				$knows_de = Db::name('knows')->field('*')->where(['id'=>$vk])->find();
			
				
				unset($knows_de['id']);
				$knows_de['admin_id'] = $_SESSION["think"]["auth_id"];
				$knows_de['admin_reg'] = $_SESSION["think"]["reg"];
				$knows_de['orid'] = $vk;
				$knows_de["k_subjectid"] = $datas_control['subjectid'][$knows_de["k_subjectid"]];
				$knows_de["k_sectionid"] = $datas_control['sectionid'][$knows_de["k_sectionid"]];
				$id = Db::name('knows')->insertGetId($knows_de);
				$datas_control['knowsid'][$vk] = $id;
				
			
			} else {
				$datas_control['knowsid'][$vk] = $vs;
			}
		
		}
	
		/****获取当前题库的科目 章节 知识点 end*****/
		
		return $datas_control;
        
		
	}
    /**
     * 分题库ajax获取顶级题库允许类型
     * @author  sunman
     */
    public function ajaxGetChildrenlist(){
        // pid 为修改时选择的题库id id 为当前修改的分题库id
        $pid = $this->request->param('pid'); //顶级题库 
        // $id = $this->request->param('id'); //分题库
        if(!$pid) throw new HttpException(404, "缺少参数ID");            
        $qbank_conf = $this->model->getInfo($pid);
        // 顶级题库绑定题型 如果顶级题库选择了题型 不进入分题库
        if($qbank_conf['alltype']){
            $ratioarr = unserialize($qbank_conf['alltype']);
        }
        
        //允许题型
        $QuestypeModel = new Questype();
        $questionType = $QuestypeModel->getQuestypeList(['status'=>1,'isdelete'=>0],'id,type type_name');
        // print_r($ratioarr);exit();
        //该题库允许的题型
        $newtypearr = array();
        for($i=0; $i<count($questionType); $i++){ 
            if(isset($ratioarr['questypes'][$questionType[$i]['id']]) && $ratioarr['questypes'][$questionType[$i]['id']]==1){
                $newtypearr[] = $questionType[$i];
            }
        }
        // var_dump($newtypearr);
        // 返回
        return json_encode($newtypearr);
    }
}
